<template>
    <tm-app class="app" color="#F5F3EF">
        <Navbar :fontSize="40" title="记录人生大事件" color="#F5F3EF" :shadow="0">
            <template v-slot:right>
                <tm-text @click="handleSubimit" class="mr-40" :font-size="32" color="#A37C3D" label="确定"></tm-text>
            </template>
        </Navbar>
        <view class="container">
            <view v-if="lifeEvents.length" class="card">
                <TimeLine :timeLineData="timeLineData" @clear="handleClear" clear />
            </view>
            <view class="date" @click="showTimePickerView = !showTimePickerView">
                <tm-icon color="#A37C3D" name="tmicon-calendar-alt"></tm-icon>
                <tm-text class="ml-20 mr-12" :font-size="36" color="#A37C3D" :label="`${yearFromat}年`"></tm-text>
                <tm-icon color="#A37C3D" :font-size="24" name="tmicon-angle-down"></tm-icon>
            </view>
            <view class="picker">
                <tm-side-menu :height="836" disabledPull :fontSize="32" disabledBottom v-model:active="active"
                    menuActiveFontColor="#333333" menuFontColor="black" menuBarBgColor="#F5F1EA" :itemHeight="100"
                    :list="typeList" @change="handleMenuChange">
                    <view class="pick-content">
                        <view class="title">
                            <tm-text :font-size="32" color="#333333" label="家庭生活"></tm-text>
                        </view>
                        <view class="content">
                            <view @click="handleTagChange(item)" class=" tag mr-28 mb-28"
                                :class="{ checked: currentLifeEvent.includes(item.dictLabel) }" :key="i"
                                v-for="(item, i) in eventList">
                                {{ item.dictLabel }}
                            </view>
                        </view>
                    </view>
                </tm-side-menu>
            </view>
        </view>

        <tm-time-picker :defaultValue="formInfo.date" v-model="formInfo.date" v-model:show="showTimePickerView"
            :show-detail="{ year: true, month: false, day: false }"></tm-time-picker>
    </tm-app>
</template>
<script setup lang="ts">
    import { ref, onMounted, computed, getCurrentInstance } from 'vue'
    const showTimePickerView = ref(false)
    import Navbar from '@/components/navbar/index.vue';
    import TimeLine from '../components/PersonalInfo/TimeLine/PersonalTimeline.vue';
    import { useLifeMilestoneStore } from '@/stores/lifeMilestone';
    import { CHANGE_EVENT } from '@/constants/events';
    import dayjs from 'dayjs';
    import { pageLink } from '@/constants/link';

    const lifeMilestoneStore = useLifeMilestoneStore()
    const instance = getCurrentInstance().proxy
    const eventChannel = instance.getOpenerEventChannel();
    const formInfo = ref({
        date: dayjs().format('YYYY-MM-DD'),
    })
    const lifeEvents = ref([])
    const active = ref(0)
    const typeList = ref([])
    const eventList = ref([])
    const isClean = ref(false)

    const yearFromat = computed(() => {
        return dayjs(formInfo.value.date).format('YYYY')
    })

    const currentLifeEvent = computed(() => {
        const currentLifeEvent = lifeEvents.value?.find((item) => item.milestoneDate === yearFromat.value)
        return currentLifeEvent?.milestoneEvent || []
    })

    const timeLineData = computed(() => {
        return lifeEvents.value?.map((item) => {
            return {
                date: item.milestoneDate,
                dictValue: item.milestoneEvent.join('、'),
            }
        })
    })

    const getTypeList = async (type) => {
        if (type) {
            const res = await lifeMilestoneStore.getMilestoneTypeList(type)
            eventList.value = res
            return
        }
        const res = eventList.value = await lifeMilestoneStore.getMilestoneTypeList('lxyd_milestone_type')
        typeList.value = (res || [])?.map((item) => {
            return {
                text: item.dictLabel,
                id: item.dictValue,
            }
        })
    }

    const handleMenuChange = (index) => {
        if (!typeList.value?.[index]) return
        const type = typeList.value?.[index]?.id
        getTypeList(type)
    }

    const handleTagChange = (val) => {
        const currentLifeEvent = lifeEvents.value?.find((item) => item.milestoneDate === yearFromat.value)
        if (currentLifeEvent) {
            const events = currentLifeEvent.milestoneEvent
            if (events.includes(val.dictLabel)) {
                currentLifeEvent.milestoneEvent = events.filter((item) => item !== val.dictLabel)
                return
            }
            if (currentLifeEvent.milestoneEvent.length >= 5) {
                uni.showToast({
                    title: '最多只能选择5个',
                    icon: 'none',
                })
                return
            }
            currentLifeEvent.milestoneEvent.push(val.dictLabel)
            return
        }
        lifeEvents.value.push({
            milestoneDate: yearFromat.value,
            milestoneEvent: [val.dictLabel],
        })
    }

    const init = async () => {
        lifeEvents.value = await lifeMilestoneStore.list()
        if (lifeEvents.value.length) isClean.value = true
        await getTypeList()
        if (!typeList.value.length) return
        const type = typeList.value?.[0]?.id
        getTypeList(type)
    }

    const handleClear = async (item) => {
        lifeEvents.value = lifeEvents.value.filter((lifeEvent) => lifeEvent.milestoneDate !== item.date)
    }

    const handleSubimit = async () => {
        const res = await lifeMilestoneStore.add(lifeEvents.value, isClean.value)
        eventChannel.emit('acceptDataFromOpenedPage', {
            page: pageLink.lifeInfo,
            event: CHANGE_EVENT,
        });
        uni.showToast({
            title: '保存成功',
            icon: 'none',
        })
        uni.navigateBack()
    }

    onMounted(async () => {
        init()
    })
</script>
<style lang="less" scoped>
    .container {
        .card {
            padding: 26rpx;
            margin: 0 40rpx;
            background-color: #fff;
            border-radius: 8rpx;
        }

        .date {
            display: flex;
            align-items: center;
            margin: 28rpx 40rpx 20rpx;
        }

        .pick-content {
            padding: 22rpx 28rpx;

            .title {
                margin-bottom: 28rpx;
            }

            .content {
                display: flex;
                flex-wrap: wrap;
            }

            .tag {
                background-color: rgba(245, 241, 234, 1);
                border-radius: 66rpx;
                padding: 12rpx 20rpx;
                font-size: 32rpx;

                &.checked {
                    background-color: rgba(163, 124, 61, 1);
                    color: #fff;
                }
            }
        }
    }
</style>